%Assign Weather (precipitation and temperature) to each individual

%input files: App_Users_Demographic.csv
%             PRECIPITATION.mat
%             TMAX.mat
%             WeatherStations.mat

%Output files:  PRECIPITATION_mat
%               TMAX_mat

load PRECIPITATION 
load TMAX_DATA 
load WeatherStations 
App_Users_in_Graph_demographics=dataset('File','App_Users_in_Graph_demographics.txt'); 
appusers=App_Users_in_Graph_demographics;

%first find for each individual the stations that are in distance 30km away.
Individual_stations=[];
for i=1:length(appusers);
    Individual_stations(i).appuser_num=i;
    d=Distance(appusers.LAT(i),appusers.LON(i),WeatherStations.LAT,WeatherStations.LON);
    closestations=find(d=<30);
    h=d(find(d=<30));
    [k,l]=sort(h);
    
    Individual_stations(i).closestations=closestations(l);
    if mod(i,1000)==0
        i
    end
end

%then assign the weather of the closest station. If some weather values are
%missing, we get them from the next closest station and so on.
PRECIPITATION_mat=nan(length(PRECIPITATION(1).PRCP),length(appusers));
TMAX_mat=nan(length(PRECIPITATION(1).PRCP),length(appusers));
TMIN_mat=nan(length(PRECIPITATION(1).PRCP),length(appusers));

for i=1:length(appusers)
    if length(Individual_stations(i).closestations)>0
    pmat=zeros(length(PRECIPITATION(1).PRCP),length(Individual_stations(i).closestations)) ;
    tmaxmat=zeros(length(PRECIPITATION(1).PRCP),length(Individual_stations(i).closestations)) ;
    tminmat=zeros(length(PRECIPITATION(1).PRCP),length(Individual_stations(i).closestations)) ;
    for j=1:length(Individual_stations(i).closestations)
        pmat(:,j)=PRECIPITATION(Individual_stations(i).closestations(j)).PRCP(:,2);
        tmaxmat(:,j)=TMAX_DATA(Individual_stations(i).closestations(j)).TMAX(:,2);
    end
    
    pvec=pmat(:,1);
    tmaxvec=tmaxmat(:,1);
    
    for j=2:length(pmat(1,:))
        pvec(find(isnan(pvec)))=pmat(find(isnan(pvec)),j);
        tmaxvec(find(isnan(tmaxvec)))=tmaxmat(find(isnan(tmaxvec)),j);
    end
    PRECIPITATION_mat(:,i)=pvec;
    TMAX_mat(:,i)=tmaxvec;
    
    else
        i
    end
    
    
end


 save PRECIPITATION_mat.mat PRECIPITATION_mat -v7.3
 save TMIN_mat.mat TMIN_mat -v7.3
 
 
 %PRECIPITATION_mat is a matrix with size: the number of days 2449 times
 %the number of individuals. For example PRECIPITATION_mat(60,1000) is the
 %total daily precipitation on the 60th day of consideration that the individual with the
 %user_num=1000 experienced. 